/*
 * @Author: 
 * @Date: 2025-06-11 14:15:05
 * @LastEditTime: 2025-08-21 12:13:52
 * @Description: 
 */
import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; // 引入Provider（如果项目中已使用）
import '../system/fontsize_provider.dart'; // 根据实际路径调整

class BatchPickingScreen extends StatefulWidget {
  const BatchPickingScreen({super.key});

  @override
  _BatchPickingScreenState createState() => _BatchPickingScreenState();
}

class _BatchPickingScreenState extends State<BatchPickingScreen> {
  final _barcodeController = TextEditingController();
  final FocusNode _barcodeFocusNode = FocusNode();
  bool _isButtonEnabled = false;
  
  // 选中的LPN值（支持null表示未选中）
  String? selectedLpn;
  
  // 可用LPN列表
  final List<String> waves = [
    'WAV-0001210-99129911',
    'WAV-0001210-99129912',
    'WAV-0001210-99129913',
    'WAV-0001210-99129914',
    'WAV-0001210-99129915',
    'WAV-0001210-99129916',
  ];

  // 新增：字体大小相关参数（与CycleCountScreen保持一致）
  double baseFontSize = 13;
  double listFontSize = 12;
  late double _fontScale;

  @override
  void dispose() {
    _barcodeController.removeListener(_updateButtonState);
    _barcodeController.dispose();
    _barcodeFocusNode.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    // 初始化选中第一项（可选，根据需求调整）
    selectedLpn = waves.first;
    _barcodeController.text = selectedLpn!;
    _barcodeController.addListener(_updateButtonState);
    
    // 页面加载后自动获取焦点
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_barcodeFocusNode);
    });
  }

  void _updateButtonState() {
    final hasText = _barcodeController.text.trim().isNotEmpty;
    if (_isButtonEnabled != hasText) {
      setState(() {
        _isButtonEnabled = hasText;
      });
    }
  }

  // 新增：处理Wave选择（支持再次点击取消）
  void _handleWaveSelection(String waveItem) {
    setState(() {
      if (selectedLpn == waveItem) {
        // 再次点击已选中项，取消选中
        selectedLpn = null;
        _barcodeController.clear();
      } else {
        // 选中新项
        selectedLpn = waveItem;
        _barcodeController.text = waveItem;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // 新增：获取字体缩放比例（与CycleCountScreen保持一致）
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;

    return Scaffold(
      appBar: AppBar(
        title: const Text('Batch Picking'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () => Navigator.pushNamed(context, '/home'),
          ),
        ],
        backgroundColor: const Color(0xFF008363)
      ),
      // 添加GestureDetector处理空白区域点击
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        behavior: HitTestBehavior.opaque,
        child: Padding(
          padding: const EdgeInsets.all(32),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // 可用LPN标题（调整样式与CycleCountScreen一致）
              Text(
                'Waves:',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: baseFontSize * _fontScale
                ),
              ),
              const SizedBox(height: 10), // 新增：与列表保持间距
              
              // Wave列表（替换为ListTile实现）
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey, width: 1.0),
                    borderRadius: BorderRadius.circular(4.0),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(4.0),
                    child: ListView.builder(
                      itemCount: waves.length,
                      itemBuilder: (context, index) {
                        final wav = waves[index];
                        return ListTile(
                          title: Text(
                            wav,
                            style: TextStyle(
                              fontSize: listFontSize * _fontScale,
                              fontWeight: FontWeight.bold,
                              // 选中时文字为绿色，未选中为黑色（与CycleCountScreen一致）
                              color: selectedLpn == wav ? Colors.green : Colors.black,
                            ),
                          ),
                          // 选中时背景为浅绿色（与CycleCountScreen一致）
                          tileColor: selectedLpn == wav ? Colors.green[50] : null,
                          onTap: () => _handleWaveSelection(wav),
                          contentPadding: const EdgeInsets.symmetric(horizontal: 16), // 统一内边距
                        );
                      },
                    ),
                  ),
                ),
              ),
              
              // WAV输入框和按钮
              _buildLpnInputSection(),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: _isButtonEnabled ? () => _submitwave(_barcodeController.text) : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF008363),
                  padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                ),
                child: const Text(
                  'OK',
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: Colors.white),
                ),
              ),
              
              const SizedBox(height: 10),
              ElevatedButton(
                onPressed: _isButtonEnabled ? () => _viewDetail(_barcodeController.text) : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF008363),
                  padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                ),
                child: const Text(
                  'Details',
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: Colors.white),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建LPN输入部分
  Widget _buildLpnInputSection() {
    return Padding(
      padding: const EdgeInsets.only(top: 20),
      child: Row(
        children: [
          Expanded(
            child: SizedBox(
              height: 30, // 与CycleCountScreen输入框高度一致
              child: TextField(
                focusNode: _barcodeFocusNode,
                controller: _barcodeController,
                decoration: const InputDecoration(
                  labelText: 'Wave',
                  labelStyle: TextStyle(fontSize: 12),
                  border: OutlineInputBorder(),
                  contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10), // 调整内边距
                ),
                style: TextStyle(fontSize: baseFontSize * _fontScale), // 统一字体大小
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _submitwave(String value) {
    if (value.isNotEmpty) {
      Navigator.pushNamed(
        context,
        '/outbound/bin-assignment',
        arguments: {'Order': value},
      );
    }
  }

  void _viewDetail(String value) {
    if (value.isNotEmpty) {
      Navigator.pushNamed(
        context,
        '',
        arguments: {'Order': value},
      );
    }
  }
}